<template>
  <div class="RequirementRelease">
    <h2>发布需求</h2>

    <div class="main">
      <a-form :form="form" @submit="handleSubmit">
        <h3>基本信息</h3>

        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="需求名称">
          <a-input :maxLength=101 v-decorator="[
              'demandProductName',
              { rules: [
                { required: true,message:'请输入需求名称' },
                { max:100,message:'该内容最多为100个字'}] },
              ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="产品同义名称">
          <a-input :maxLength=101 v-decorator="[
              'productSynonymName',
              { rules: [{ max:100,message:'该内容最多为100个字'}] },
            ]" />
          <em>多个名称使用分隔符(;)进行区分</em>
        </a-form-item>
        <a-form-item required :label-col="formTailLayout.labelCol" :wrapper-col="{span:15}" label="产品类别">
          <div class="clearfix">
            <a-form-item class="f-left mr-32">
              <a-select placeholder="请选择" style="width: 250px" @change="handleChange" v-decorator="['productOneCategory',{ rules: productOneCategoryRules}]">
                <a-select-option v-for="(item,index) in selectType" :key="index" :value="item.categoryNo">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="f-left mr-32">
              <a-select placeholder="请选择" style="width: 250px" @change="handleChange1" v-decorator="['productSecondCategory',{ rules: productSecondCategoryRules},]">
                <a-select-option v-for="(item, index) in selectType1" :key="index" :value="item.categoryNo">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="f-left">
              <a-input :maxLength=101 style="width:250px" v-decorator="[
                    'productThirdCategory',
                    { rules: [{ max:100,message:'该内容最多为100个字'}] },
                  ]" />
            </a-form-item>
            <!-- </a-form-item> -->
          </div><em>可输入小类，多个名称使用分隔符（;）进行区分</em>
        </a-form-item>
        <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol" label="规格型号">
          <a-input :maxLength=1001 type="textarea" :rows="5" v-decorator="[
                'productSpec',
                { rules: [
                  { required: true,message:'请输入规则型号' },
                  { max:1000,message:'该内容最多为1000个字'}
                ] },
              ]" /><em>多个名称使用分隔符(;)进行区分</em>
        </a-form-item>
        <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol" label="概述">
          <a-input type="textarea" :rows="5" v-decorator="[
                'demandDetails',
              ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="{span:4}" label="预算价格">
          <a-input suffix="元" v-decorator="['price',{rules: [
          { 
            pattern:/^(\+)?\d+(\.\d+)?$/,
            message:'该内容必须为数字' 
          }
          ],},]" />
        </a-form-item>
        <a-form-item class="clearfix" required :label-col="formItemLayout.labelCol" :wrapper-col="{span:8}" label="截止时间">
          <a-date-picker class="f-left" @change="dataChange" :disabled-date="disabledDate" v-decorator="[
            'expirationDate',
            { rules: dataRules},
          ]" />
          <a-form-item class="f-left ml-20">
            <a-checkbox :checked="checkNick" @change="checkChange" v-decorator="['isLongTime']">长期需求</a-checkbox>
          </a-form-item>
        </a-form-item>

        <h3>联系方式</h3>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="联系人">
          <a-input v-decorator="[
              'contacts',
              { rules: [{ required: true,message:'请输入联系人' }],
              initialValue:infoList.contacts },
            ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="手机号码">
          <a-input v-decorator="[
              'phone',
              { rules: [
                { required: true,message:'请输入手机号码' },
                {
                  pattern:  /^1[3456789]\d{9}$/,
                  message: '手机号码格式不正确'
                }
              ],initialValue:infoList.phone  },
            ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="电子邮箱">
          <a-input v-decorator="[
              'email',
              { rules:[
                {
                  pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
                  message: '邮箱格式不正确'
              }],initialValue:infoList.email}
            ]" />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 4 }">
          <a-button class="mr-20" @click="returnBtn">
            返回
          </a-button>
          <a-button class="mr-20" @click="clear">
            重置
          </a-button>
          <a-button :disabled="IsDisable" type="primary" html-type="submit">
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { GetByParent, AddMaterialsDemand } from "@/apis/user/MaterialsDemand";
import { getEntBaseInfo } from "@/apis/user/EntBaseInfo";
const formItemLayout = {
  //label长度
  labelCol: { span: 4 },
  //input长度
  wrapperCol: { span: 8 },
};
const formTailLayout = {
  //label长度
  labelCol: { span: 4 },
  //input长度
  wrapperCol: { span: 12 },
};
export default {
  data() {
    return {
      IsDisable: false,
      productOneCategoryRules: [{ required: true, message: "请选择一级类别" }],
      productSecondCategoryRules: [
        { required: false, message: "请选择二级类别" },
      ],
      dataRules: [{ required: true, message: "请输入截止日期" }],
      checkNick: false,
      selectType: [],
      selectType1: [],
      isLongTime: 1,
      formItemLayout,
      formTailLayout,
      form: this.$form.createForm(this),
      formLine: {},
      infoList: {},
    };
  },
  created() {
    this.GetByParentList();
    this.getEntBaseInfo();
  },
  methods: {
    //日期判断今天之前不可选（不包含今天）
    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().subtract(1, "days").endOf("day");
    },
    //获取企业基本信息
    getEntBaseInfo() {
      getEntBaseInfo().then((res) => {
        console.log("获取企业信息");
        console.log(res);
        if ((res.code == 200)) {
          this.infoList = res.data;
        }
      });
    },
    dataChange(e) {
      console.log(e);
      if (e == null) {
        // this.dataRules[0].required = true
        this.checkNick = true;
        this.isLongTime = 1;
      } else {
        this.dataRules[0].required = false;
        this.checkNick = false;
        this.isLongTime = 0;
      }
    },
    checkChange(e) {
      this.checkNick = e.target.checked;
      if (this.checkNick) {
        this.dataRules[0].required = false;
        this.isLongTime = 1;
      } else {
        this.dataRules[0].required = true;
        this.isLongTime = 0;
      }
      this.form.setFieldsValue({
        expirationDate: "",
      });
    },
    handleSubmit(e) {
      console.log(e);
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          values.isLongTime = this.isLongTime;
          if (values.expirationDate) {
            values.expirationDate = moment(values.expirationDate).format(
              "YYYY-MM-DD"
            );
          }

          this.formLine = values;
          console.log(this.formLine);
          this.AddMaterialsDemand();
        }
      });
    },
    returnBtn() {
      //跳回需求页
      this.$router.push("/usercenter/MyNeed");
    },
    clear() {
      // 清空表单
      this.form.resetFields();
      this.checkNick = false;
    },
    // 新增
    AddMaterialsDemand() {
      // let params = {
      //   // demandProductName,//产品名称
      //   // productSynonymName,//同义名称
      //   // productOneCategory,//一级分类
      //   // productSecondCategory,//二级分类
      //   // productThirdCategory,//三级分类
      //   // productSpec,//产品规则
      //   // demandDetails，//详情
      //   // price,//价格
      //   // expirationDate,//截止日期
      //   // isLongTime,//是否长期
      //   // contacts,//联系人
      //   // phone,//联系电话
      //   // email,//电子邮箱
      // }
      this.IsDisable = true;
      AddMaterialsDemand(this.formLine)
        .then((res) => {
          console.log(res);
          this.IsDisable = false;
          if (res.code == 200) {
            this.$message.success("提交成功");
            setTimeout(() => {
              //跳回需求页
              this.$router.push("/usercenter/MyNeed");
            }, 1000);
          } else {
            this.$message.warning("新增失败");
          }
        })
        .catch((error) => {
          this.IsDisable = false;
        });
    },
    // 产品分类下拉列表
    GetByParentList() {
      GetByParent().then((res) => {
        // console.log(res)
        if (res.code == 200) {
          this.selectType = res.data.filter(ele => ele.categoryStatus === 1)
        }
      });
    },
    handleChange(value) {
      console.log(value);
      this.productOneCategoryRules[0].required = true;
      this.productSecondCategoryRules[0].required = true;
      let id = "";
      this.selectType.map((item, index) => {
        if (item.categoryNo == value) {
          id = item.id;
        }
      });
      let params = { pid: id };
      GetByParent(params).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.selectType1 = res.data.filter(ele => ele.categoryStatus === 1)
          this.form.setFieldsValue({
            productSecondCategory: null,
          });
        }
      });
    },
    handleChange1(value) {
      console.log(value);
    },
  },
};
</script>

<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 8px;
}
.RequirementRelease {
  padding: 17px 24px;
  background: #fff;
  h2 {
    font-size: 22px;
    line-height: 17px;
    color: #303133;
    padding-bottom: 14px;
    border-bottom: solid 1px #e9e9e9;
  }

  .main {
    h3 {
      margin: 16px 0;
      padding-left: 16px;
      height: 48px;
      line-height: 48px;
      font-weight: 700;
      font-size: 16px;
      color: #303133;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
}
em {
  font-size: 14px;
  color: #909399;
}
</style>